'''
Created on 06/04/2009

@author: Edward
'''
from im.ds import dsconstants, dsofactory
from im.ds.dsstub import DSStub
from im.event import eventconstants
from im.event.event import Event
from im.event.eventhandler import BaseEventHandler
from im.event.eventmanager import EventManager
import httplib
import datetime
import os

class ResponseTimeoutHandler(BaseEventHandler):
    '''
    classdocs
    '''
    
    def do(self, data):
        dso = data
        request_id = dso.get_dst(subject=dsconstants.SUBJECT_ROOT, 
                                 predicate=dsconstants.PREDICATE_REQUEST_ID).get_literal()
        ds = DSStub()
        result = ds.get_outstanding_requests(int(request_id))
        if result:
            (http_request, lock) = result
        else:
            print 'Cannot find message entry with request_id ' + str(request_id)
            return
        
        fault_message = 'spear-im-not-available'

        relative_path = "../../../pages/im/imerror.html"
        
        # get the html template
        template_path = os.path.join(os.path.dirname(__file__), relative_path)
        file = open(template_path)
        html_template_string = file.read()
        html_string = html_template_string.replace('${fault_message}', fault_message)
        new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                               'text/html', 
                                                               html_string, 
                                                               http_request, 
                                                               lock)
        event = Event(eventconstants.HTTP_RESPONSE_EVENT_TYPE, new_dso)
        EventManager().add_event(event)
        print 'End Request: ' + str(datetime.datetime.now())                